{% extends "base.html" %}

{% block title %}添加错题 - 错题系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col">
        <h1><i class="bi bi-plus-circle"></i> 添加新错题</h1>
        
        <div class="card">
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="question" class="form-label">题目 *</label>
                        <div class="input-group mb-2">
                            <textarea class="form-control" id="question" name="question" rows="3" required></textarea>
                        </div>
                        <div class="input-group">
                            <input type="file" class="form-control" id="question_image" name="question_image" accept="image/*">
                            <button class="btn btn-outline-primary" type="button" id="recognize_question_btn">
                                <i class="bi bi-eye"></i> 识别题目
                            </button>
                        </div>
                        <div class="form-text">可以手动输入题目或上传图片自动识别</div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="correct_answer" class="form-label">正确答案 *</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="correct_answer" name="correct_answer" required>
                                    <input type="file" class="form-control" id="correct_answer_image" name="correct_answer_image" accept="image/*" style="display: none;">
                                    <button class="btn btn-outline-primary" type="button" id="recognize_correct_answer_btn">
                                        <i class="bi bi-eye"></i> 识别
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="user_answer" class="form-label">你的答案 *</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="user_answer" name="user_answer" required>
                                    <input type="file" class="form-control" id="user_answer_image" name="user_answer_image" accept="image/*" style="display: none;">
                                    <button class="btn btn-outline-primary" type="button" id="recognize_user_answer_btn">
                                        <i class="bi bi-eye"></i> 识别
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="exam_type" class="form-label">考试类型</label>
                        <div class="input-group">
                            <select class="form-select" id="exam_type" name="exam_type">
                                <option value="">请选择考试类型</option>
                                {% if exam_types %}
                                    {% for exam_type in exam_types %}
                                        <option value="{{ exam_type }}">{{ exam_type }}</option>
                                    {% endfor %}
                                {% endif %}
                            </select>
                            <button class="btn btn-outline-secondary" type="button" id="add_new_type_btn">
                                <i class="bi bi-plus"></i> 添加新类型
                            </button>
                        </div>
                        <div class="form-text">可以选择已有考试类型或添加新的</div>
                    </div>
                    
                    <div class="mb-3" id="new_exam_type_group" style="display: none;">
                        <label for="new_exam_type" class="form-label">新考试类型名称</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="new_exam_type" name="new_exam_type" placeholder="输入新的考试类型名称">
                            <button class="btn btn-outline-success" type="button" id="confirm_new_type">
                                <i class="bi bi-check"></i> 确认
                            </button>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="knowledge_points" class="form-label">涉及知识点 *</label>
                        <input type="text" class="form-control" id="knowledge_points" name="knowledge_points" 
                               placeholder="多个知识点用逗号分隔" required>
                        <div class="form-text">例如：操作系统, 进程管理, 内存分配</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="explanation" class="form-label">解析 *</label>
                        <div class="input-group mb-2">
                            <textarea class="form-control" id="explanation" name="explanation" rows="4" required></textarea>
                        </div>
                        <div class="input-group">
                            <input type="file" class="form-control" id="explanation_image" name="explanation_image" accept="image/*">
                            <button class="btn btn-outline-primary" type="button" id="recognize_explanation_btn">
                                <i class="bi bi-eye"></i> 识别解析
                            </button>
                        </div>
                        <div class="form-text">可以手动输入解析或上传图片自动识别</div>
                    </div>
                    
                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                        <a href="{{ url_for('index') }}" class="btn btn-secondary">取消</a>
                        <button type="submit" class="btn btn-primary">添加错题</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- OCR识别模态框 -->
<div class="modal fade" id="ocrModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">OCR识别结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">识别内容</label>
                    <textarea class="form-control" id="ocr_result" rows="4"></textarea>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="auto_fill">
                    <label class="form-check-label" for="auto_fill">
                        自动填充到相应字段
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm_ocr">确认</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 现有的考试类型功能
        const examTypeSelect = document.getElementById('exam_type');
        const newExamTypeGroup = document.getElementById('new_exam_type_group');
        const newExamTypeInput = document.getElementById('new_exam_type');
        const addNewTypeBtn = document.getElementById('add_new_type_btn');
        const confirmNewTypeBtn = document.getElementById('confirm_new_type');
        
        // OCR相关元素
        const ocrModal = new bootstrap.Modal(document.getElementById('ocrModal'));
        const ocrResult = document.getElementById('ocr_result');
        const autoFill = document.getElementById('auto_fill');
        const confirmOcrBtn = document.getElementById('confirm_ocr');
        
        // 当前正在识别的字段
        let currentField = null;
        
        // 显示添加新类型的输入框
        addNewTypeBtn.addEventListener('click', function() {
            newExamTypeGroup.style.display = 'block';
            newExamTypeInput.focus();
        });
        
        // 确认添加新类型
        confirmNewTypeBtn.addEventListener('click', function() {
            const newType = newExamTypeInput.value.trim();
            
            if (newType) {
                // 检查是否已经存在同名选项
                let optionExists = false;
                for (let i = 0; i < examTypeSelect.options.length; i++) {
                    if (examTypeSelect.options[i].text === newType) {
                        optionExists = true;
                        examTypeSelect.selectedIndex = i;
                        break;
                    }
                }
                
                // 如果不存在，则添加新选项
                if (!optionExists) {
                    const newOption = new Option(newType, newType);
                    examTypeSelect.add(newOption);
                    examTypeSelect.value = newType;
                }
                
                // 隐藏输入框并清空内容
                newExamTypeGroup.style.display = 'none';
                newExamTypeInput.value = '';
            } else {
                alert('请输入新的考试类型名称');
                newExamTypeInput.focus();
            }
        });
        
        // 回车键确认添加新类型
        newExamTypeInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                confirmNewTypeBtn.click();
            }
        });
        
        // 表单提交前处理
        document.querySelector('form').addEventListener('submit', function(e) {
            // 如果选择了新类型但该类型不存在于选项中，则当作新类型处理
            const selectedValue = examTypeSelect.value;
            let optionExists = false;
            
            for (let i = 0; i < examTypeSelect.options.length; i++) {
                if (examTypeSelect.options[i].value === selectedValue) {
                    optionExists = true;
                    break;
                }
            }
            
            // 如果选项不存在，说明是新增的类型，需要设置隐藏字段
            if (!optionExists && selectedValue) {
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'new_exam_type';
                hiddenInput.value = selectedValue;
                this.appendChild(hiddenInput);
            }
        });
        
        // OCR识别功能
        document.querySelectorAll('[id$="_btn"]').forEach(button => {
            button.addEventListener('click', function() {
                const fieldId = this.id.replace('_btn', '');
                const imageInput = document.getElementById(fieldId);
                
                if (imageInput && imageInput.files.length > 0) {
                    // 模拟OCR识别过程
                    currentField = fieldId.replace('_recognize', '');
                    performOCR(imageInput.files[0]);
                } else {
                    // 显示文件选择框
                    const fileInput = document.getElementById(fieldId + '_image');
                    if (fileInput) {
                        fileInput.click();
                        fileInput.onchange = () => {
                            if (fileInput.files.length > 0) {
                                currentField = fieldId.replace('_recognize', '');
                                performOCR(fileInput.files[0]);
                            }
                        };
                    }
                }
            });
        });
        
        // 模拟OCR识别
        function performOCR(file) {
            // 在实际应用中，这里会发送请求到OCR服务
            // 现在我们模拟识别结果
            const reader = new FileReader();
            reader.onload = function(e) {
                // 模拟OCR识别结果
                const mockResults = {
                    'question': '在操作系统中，进程调度算法的主要目的是什么？\nA. 提高内存利用率\nB. 提高CPU利用率\nC. 减少进程数量\nD. 增加系统复杂性',
                    'correct_answer': 'B',
                    'user_answer': 'A',
                    'explanation': '进程调度算法的主要目的是提高CPU的利用率，通过合理地分配CPU时间给各个进程，使得CPU尽可能处于忙碌状态，从而提高系统整体性能。'
                };
                
                // 根据字段显示相应模拟结果
                let result = '';
                if (currentField.includes('question')) {
                    result = mockResults.question;
                } else if (currentField.includes('correct_answer')) {
                    result = mockResults.correct_answer;
                } else if (currentField.includes('user_answer')) {
                    result = mockResults.user_answer;
                } else if (currentField.includes('explanation')) {
                    result = mockResults.explanation;
                } else {
                    result = '这是OCR识别的结果内容，根据实际图片内容会有所不同。';
                }
                
                ocrResult.value = result;
                autoFill.checked = true;
                ocrModal.show();
            };
            reader.readAsDataURL(file);
        }
        
        // 确认OCR结果
        confirmOcrBtn.addEventListener('click', function() {
            if (autoFill.checked) {
                // 自动填充到对应字段
                const targetField = document.getElementById(currentField);
                if (targetField) {
                    targetField.value = ocrResult.value;
                }
            }
            ocrModal.hide();
        });
    });
</script>
{% endblock %}